package controller.services.impl;

import controller.services.PlaylistPersistenceService;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.mp3.MP3Info;
import model.mp3.MP3Object;
import model.mp3.impl.MP3InfoImpl;
import model.mp3.impl.MP3ObjectImpl;

public class PlaylistPersistenceServiceImpl implements PlaylistPersistenceService {

    private FileOutputStream saveFOS;
    private ObjectOutputStream saveOutputStream;

    private void openConnection() {
        try {
            saveFOS = new FileOutputStream("playlistSave.vtpl");
            saveOutputStream = new ObjectOutputStream(saveFOS);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(PlaylistPersistenceServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PlaylistPersistenceServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void saveData(List<MP3Object> playlist) {
        try {

            openConnection();
            saveOutputStream.writeObject(playlist);
            // Close the file.
            saveOutputStream.close(); // This also closes saveFile.
            System.out.println("saved playlist with " + playlist.size() + " elements");
        } catch (IOException ex) {
            Logger.getLogger(PlaylistPersistenceServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public List<MP3Object> readData() {
         File file = new File("playlistSave.vtpl");
         if (file.exists() ==false) {
            saveData(new ArrayList<MP3Object> ());
         }
        
        try {
            FileInputStream fis = new FileInputStream("playlistSave.vtpl");
            ObjectInputStream restore = new ObjectInputStream(fis);
            List<MP3Object> obj = (List<MP3Object>) restore.readObject();
            return obj;
        } catch (FileNotFoundException ex) {
             saveData(new ArrayList<MP3Object> ());
            
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(PlaylistPersistenceServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

}
